import { ref } from "vue";
const dragscroll = (el) => {
  const isDragging = ref(false);
  el.onmousedown = (ev) => {
    isDragging.value = false;
    const disX = ev.clientX;
    const disY = ev.clientY;
    const originalScrollLeft = el.scrollLeft;
    const originalScrollTop = el.scrollTop;
    const originalScrollBehavior = el.style["scroll-behavior"];
    const originalPointerEvents = el.style["pointer-events"];
    el.style["scroll-behavior"] = "auto";

    const onMouseMove = (dv) => {
      dv.preventDefault();
      isDragging.value = true;
      const distanceX = dv.clientX - disX;
      const distanceY = dv.clientY - disY;
      el.scrollTo(originalScrollLeft - distanceX, originalScrollTop - distanceY);
    };

    const onMouseUp = () => {
      document.removeEventListener("mousemove", onMouseMove);
      document.removeEventListener("mouseup", onMouseUp);
      el.style["scroll-behavior"] = originalScrollBehavior;
      el.style["pointer-events"] = originalPointerEvents;

      // 使用延时器在鼠标释放后的一小段时间内保持 isDragging 为 true
      setTimeout(() => {
        isDragging.value = false;
      }, 50);
    };

    document.addEventListener("mousemove", onMouseMove);
    document.addEventListener("mouseup", onMouseUp);
  };

  el.addEventListener(
    "click",
    (ev) => {
      if (isDragging.value) {
        ev.stopImmediatePropagation();
        ev.preventDefault();
      }
    },
    true,
  ); // 使用捕获阶段的事件监听器
};

export default {
  mounted(el) {
    dragscroll(el);
  },
};
